/**
 * 报表管理页
 */
var sql;

var index = 1;

var type="root";

var ReportManager = function(url, sysId, nodeId,rootNodeId, remind, templatenotexist,
                             savesuccess, savefailure, choosedatasource, determine, setdatsource,
                             outterdatasource, cancle) {
    this.url = url;
    this.sysId = sysId;
    this.nodeId = $("#" + nodeId);
    this.rootNodeId = $("#" + rootNodeId);
    this.loadReportTree(remind, templatenotexist, savesuccess, savefailure);
    this.loadReportTreeRoot(remind, templatenotexist, savesuccess, savefailure);
    this.init(choosedatasource, determine, setdatsource, outterdatasource,
        cancle);
};

/**
 * choosedatasource选择数据源
 * determine'确定'
 * setdatsource 新建模板-设置数据源
 * outterdatasource 新建模板-外部数据源
 * cancle 取消
 */
ReportManager.prototype.init = function() {
    var _url = this.url;
    var _sysId = this.sysId;
    var _nodeId = this.nodeId;
    var _rootNodeId = this.rootNodeId;
    // 初始化数据源选择对话框
    $("#dataSourceSelectDialog").dialog({
        title : commonLang.tip.chooseDataSource,
        width : 400,
        height : 200,
        closed : true,
        modal : true,
        resizable : true,
        buttons : [{
            text : commonLang.tip.determine,
            handler : function() {
                $("#dataSourceSelectDialog").dialog('close');
                var node;
                if(type == "root"){
                    node = _rootNodeId.tree('getSelected');
                }else{
                    node = _nodeId.tree('getSelected');;
                }
                var args = {
                    sysId : _sysId,
                    parentId : node.id,
                    type : $("#dataSourceSelectDialog")
                        .find("input:checked")
                        .val()
                };
                var title = "";
                if ('0' == args.type) {
                    //
                    title = commonLang.tip.setDataSource;
                } else {
                    //
                    title = commonLang.tip.outterDataSource;
                }

                var dialogId = "dataSourceConfigDialog";
                var config = new CommonDialog(dialogId,
                    "900", "450", _url
                    + "/datasourcetype"
                    + "?dialogId="
                    + dialogId + "&sysId="
                    + args.sysId + "&type="
                    + args.type
                    + "&parentId="
                    + args.parentId, title,
                    false, true, false, false,
                    false);
                config.show();

            }
        },
            {
                text : commonLang.tip.cancle,
                handler : function() {
                    $("#dataSourceSelectDialog").dialog(
                        'close', true);
                }
            } ]

    });
};


// 给IFRAME窗口提供公用的参数
ReportManager.prototype.getCommArgs = function() {
    return {
        url : this.url,
        sysId : this.sysId
    };

};

// 设计器
ReportManager.prototype.fineReport = function() {

    $.messager.alert('提示',
        $(
            $(window.frames["reportView"].document).find("#r-0-0")
                .find("td")[0]).text(), 'warning');

};

// 导入
/**
 * commonLang.tip.alert:提示 selecttemplateupload:请选择一个分类进行模板上传! import:导入
 */
ReportManager.prototype.importData = function() {
    var _nodeId;
    if(type == "root"){
        _nodeId = this.rootNodeId;
    }else{
        _nodeId = this.nodeId;
    }
    var node = _nodeId.tree('getSelected');
    if (null == node || node.attributes.reportType == '1') {
        $.messager.alert(commonLang.tip.alert,
            commonLang.tip.selectTemplateUpload, 'warning');
        return;
    }
    var nodeId = node.id;
    var dialogId = "ReportImportDialog";
    var toActionUrl = 'avicit/im/lantop/basic/reportmanager/ReportManagerImport.jsp?sysId='
        + this.sysId + '&_parentId=' + nodeId + "&dialogId=" + dialogId;
    var usdImport = new CommonDialog(dialogId, "530", "220", toActionUrl,
        commonLang.tip.importIn, false, true, false);
    usdImport.show();
};

// 导出
/**
 * commonLang.tip.alert:提示 selecttemplateexport:请选择一个模板进行导出！
 * templatenotexist:模板文件不存在！
 */
ReportManager.prototype.exportData = function() {
    var _nodeId;
    if(type == "root"){
        _nodeId = this.rootNodeId;
    }else{
        _nodeId = this.nodeId;
    }
    var node = _nodeId.tree('getSelected');

    if (null == node || node.attributes.reportType == '0') {
        $.messager.alert(commonLang.tip.alert,
            commonLang.tip.selectTemplateExport, 'warning');
        return;
    }
    var reportName = node.attributes.cptFileName;
    var cptFileExist = node.attributes.cptFileExist;

    if (reportName == undefined || null == reportName || !cptFileExist) {
        $.messager.alert(commonLang.tip.alert, commonLang.tip.templateNotExist,
            'warning');
        return;

    }
    // 下载文件
    window.location.href = baseHref
        + "platform/im/lantop/basic/ReportManagerController/filedownload?reportName="
        + encodeURI(encodeURI(reportName));

};

// 报表属性
ReportManager.prototype.propertyReport = function() {

    alert("未实现");

};

// 预览报表
// commonLang.tip.alert:提示
// selectTemplate:请选择一个模板预览！
// commonLang.tip.reportPreview:报表预览
ReportManager.prototype.previewReport = function(remind, selectTemplate,
                                                 viewReport) {
    var _nodeId;
    if(type == "root"){
        _nodeId = this.rootNodeId;
    }else{
        _nodeId = this.nodeId;
    }
    var node = _nodeId.tree('getSelected');

    if (node == null || node.length == 0 || node.attributes.reportType == '0') {
        $.messager.alert(commonLang.tip.alert, commonLang.tip.selectTemplate,
            'warning');
        return;
    }

    var reportName = node.attributes.cptFileName;

    // 对于没有配置数据源的模板，进行预览
    var paramNames = [];

    paramNames.push('reportlet');
    paramNames.push('SQL');

    var paramValues = [];

    paramValues.push(cjkEncode(reportName));
    paramValues.push("SELECT ' ' FROM DUAL");
    var fulls = "left=0,screenX=0,top=0,screenY=0,scrollbars=1,toolbar=yes,menubar=1"; // 定义弹出窗口的参数
    if (window.screen) {
        var ah = screen.availHeight - 30;
        var aw = screen.availWidth - 10;
        fulls += ",height=" + ah;
        fulls += ",innerHeight=" + ah;
        fulls += ",width=" + aw;
        fulls += ",innerWidth=" + aw;
        fulls += ",resizable";
    } else {
        fulls += ",resizable"; // 对于不支持screen属性的浏览器，可以手工进行最大化。 manually
    }
    window
        .open(
            baseHref
            + "platform/im/lantop/basic/ReportManagerController/toPreviewPrintPageJsp?reportlet="
            + cjkEncode(reportName), 'lantop_report_print'
            + new Date().getTime(), fulls);

};

// 打印报表
ReportManager.prototype.printReport = function() {
    var _nodeId;
    if(type == "root"){
        _nodeId = this.rootNodeId;
    }else{
        _nodeId = this.nodeId;
    }
    var node = _nodeId.tree('getSelected');
    if (node == null || node.length == 0 || node.attributes.reportType == '0') {
        $.messager.alert('提示', "请选择一个模板打印！", 'warning');
        return;
    }
    if (!node.attributes.hasField) {
        $.messager.alert('提示', '当前选择模板没有配置数据源，不能进行报表打印！', 'warning');
        return;
    }
    var resultDataSource = node.attributes.resultDataSource;
    if (undefined == resultDataSource) {
        $.messager.alert('提示', '当前选择模板没有配置数据源，不能进行报表打印！', 'warning');
        return;
    }
    var reportName = encodeURI(encodeURI(node.attributes.cptFileName));
    window
        .open(
            baseHref
            + 'platform/im/lantop/basic/ReportManagerController/reportview?templateId='
            + node.id + "&reportName=" + reportName
            + "&reportViewType=1" + "&type=2", 'Derek',
            "status=yes,toolbar=yes,menubar=no,location=no'");

};

function cjkEncode(text) {
    if (text == null) {
        return "";
    }
    var newText = "";
    for ( var i = 0; i < text.length; i++) {
        var code = text.charCodeAt(i);
        if (code >= 128 || code == 91 || code == 93) { // 91 is "[", 93 is "]".
            newText += "[" + code.toString(16) + "]";
        } else {
            newText += text.charAt(i);
        }
    }
    return newText;
}

// 配置报表
/**
 * commonLang.tip.alert:提示 selectTemplateConfig:请选择一个模板进行报表配置！
 * templateNoFiled:当前选择模板没有应输出字段，不能进行报表配置！！ templateConfig:报表配置
 */
ReportManager.prototype.configReport = function() {
    var _nodeId;
    if(type == "root"){
        _nodeId = this.rootNodeId;
    }else{
        _nodeId = this.nodeId;
    }
    var template = _nodeId.tree('getSelected');
    if (null == template || template.attributes.reportType == '0') {
        $.messager.alert(commonLang.tip.alert,
            commonLang.tip.selectTemplateConfig, 'warning');
        return;
    }
    // 获取报表应输出字段, 对于导入的报表模板，需要从cpt文件中获取暂时不处理
    // 导入报表模板，获取代码
    // ($($(window.frames["reportView"].document).find("#r-0-0").find("td")[0]).text())
    // 目前直接从节点中获取
    var outPutFields;
    if (template.attributes.hasField) {
        outPutFields = template.attributes.fields;
    } else {
        outPutFields = $(
            $(window.frames["reportView"].document).find("#r-0-0").find(
                "td")[0]).text();
        if ("" == outPutFields) {
            $.messager.alert(commonLang.tip.alert,
                commonLang.tip.templateNoFiled, 'warning');
            return;
        }
    }
    outPutFields = encodeURI(encodeURI(outPutFields));
    var resultDataSource = template.attributes.resultDataSource;
    if (undefined == resultDataSource) {
        resultDataSource = "";
    }
    var dialogId = "formConfigReport";
    var config = new CommonDialog(dialogId, "900", "450",
        "platform/ReportFormConfigController/toReportFormConfigJsp?dialogId="
        + dialogId + "&sysId=" + this.sysId + "&outPutFields="
        + outPutFields + "&templateId=" + template.id
        + "&resultDataSource=" + resultDataSource,
        commonLang.tip.templateConfig, false, true, false, false, true);
    config.show();
};

// 新增模板
ReportManager.prototype.appendTemplate = function() {
    $("#dataSourceSelectDialog").dialog('open');
};

// 新增
// newclassification:新建分类
ReportManager.prototype.append = function(newclassification) {
    var _nodeId;
    if(type == "root"){
        _nodeId = this.rootNodeId;
    }else{
        _nodeId = this.nodeId;
    }
    var node = _nodeId.tree('getSelected');
    _nodeId.tree('append', {
        parent : node.target,
        data : {
            id : 'xjfl_' + index,
            text : newclassification + index,
            state : 'open',
            iconCls : '',
            _parentId : node.id,
            attributes : {
                "reportType" : '0'
            }
        }
    });
    // 根据ID查找新增的节点
    var node1 = _nodeId.tree('find', 'xjfl_' + index);
    _nodeId.tree('select', node1.target);
    // 添加完成后，开启编辑模式
    _nodeId.tree('beginEdit', node1.target);
    index++;

};

// 删除报表
/**
 * commonLang.tip.alert:提示 rootcantdelete:根节点不能删除！ suredelete:您确认删除
 * alltemplate:分类项及所有模板吗？ confirmdelete：您确认想要删除模板吗？ commonLang.tip.confirm：确认
 * deletesuccess：删除成功 deletefailure：删除失败
 */
var rootcantdelete = '根节点不能删除！';
var suredelete = '您确认删除';
var alltemplate = '分类项及所有模板吗？';
var confirmdelete = '您确认想要删除模板吗？';
var deletesuccess = '删除成功';
var deletefailure = '删除失败';
ReportManager.prototype.remove = function() {
    var _url = this.url;
    var _nodeId;
    var sysId = this.sysId;
    if(type == "root"){
        _nodeId = this.rootNodeId;
    }else{
        _nodeId = this.nodeId;
    }
    var node1 = _nodeId.tree('getSelected');
    // 根节点不能被删除
    var rootNode = _nodeId.tree('getRoot');
    if (node1 == rootNode) {
        $.messager.alert(commonLang.tip.alert, commonLang.tip.rootCantDelete,
            'warning');
        return;
    }
    var errorMsg = "";
    if (node1.attributes.reportType == '0') {
        errorMsg = commonLang.tip.sureDelete + node1.text + alltemplate;
    } else {
        errorMsg = commonLang.tip.confirmDelete;
    }
    $.messager.confirm(commonLang.tip.confirm, errorMsg, function(r) {
        if (r) {
            delete1();
        }
    });

    function delete1() {
        // 获取选中的节点
        var node = _nodeId.tree('getSelected');
        // 参数
        var args = {};
        if (node.attributes.reportType == '0') {
            // 这个是分类，需要删除分类下的所有子节点
            var ids = node.id + ",";
            $.each(node.children, function(index, value) {
                ids = ids + value.id + ",";
            });
            args = {
                id : ids
            };
        } else {
            // 是模板 ， 只删除该模板ID
            args = {
                id : node.id
            };
        }
        $.ajax({
            url : _url + "/deletereporttree",
            dataType : 'json',
            type : 'post',
            data : {
                param : JSON.stringify(args)
            },
            success : function(result) {
                if (result.flag == "success") {
                    // 删除成功 ， 刷新其父节点
                    // 保存成功 ， 刷新其父节点
                    if(type == "root"){
                        _nodeId.tree({
                            url : _url + "/gettree/-1/root?sysId="+sysId
                        });
                    }else{
                        _nodeId.tree({
                            url : _url + "/gettree/-1/null?sysId="+sysId
                        });
                    }

                    $.messager.show({
                        title : commonLang.tip.alert,
                        msg : commonLang.optip.deleteSuccess,
                        timeout : 4000,
                        showType : 'slide'
                    });
                } else {
                    $.messager.show({
                        title : commonLang.tip.alert,
                        msg : commonLang.optip.deleteFailure,
                        timeout : 4000,
                        showType : 'slide'
                    });
                }
            }
        });
    }
};

// 加载报表管理树
/**
 * remind, 提示 templatenotexist 该模板不存在！ savesuccess 保存成功 savefailure 保存失敗
 */
ReportManager.prototype.loadReportTree = function() {
    var _self = this;
    var _nodeId = this.nodeId;
    var _url = this.url;
    var _sysId = this.sysId;
    var _currentEditNodeText = null;
    this.nodeId
        .tree({
            checkbox : false, // 是否带复选框
            lines : true, // 线条
            method : 'post',
            url : this.url + "/gettree/-1/null?sysId="+_sysId,
            dataType : "json",
            /* 数据格式 */
            onCheck : function(node, checked) {
                // 勾选复选框时触发
                type="nRoot";
            },
            formatter : function(node) {
                if (node._parentId == "-1") {
                    _self._rootId = node.id;
                }
                if (node.attributes && node.attributes.s) {
                    return '<a style="color:#fff;font-weight:normal;background:#3399ff;padding:0 4px;">'
                        + node.text + '</a>';
                } else {
                    return node.text;
                }
            },
            loadFilter : function(data) {
                // 过滤后台返回的数据，处理不同JSON结构
                if (data.data) {
                    return data.data;
                } else {
                    return data;
                }
            },
            onClick : function(node) {
                _nodeId.tree('select', node.target);
                // 模板， 加载其所对应的模板
                if (node.attributes.reportType == '1') {
                    if (node.attributes.cptFileName == null
                        || !node.attributes.cptFileExist) {
                        $.messager.alert(commonLang.tip.alert,
                            commonLang.tip.templateNotExist, 'warning');
                        return;
                    }
                    lantopFineReport.submit({
                        SQL : "SELECT ' ' FROM DUAL",
                        reportlet : node.attributes.cptFileName
                    });
                }
                $("#importId").show();
                type="nRoot";
            },
            onContextMenu : function(e, node) {
                e.preventDefault();
                // 查找节点
                _nodeId.tree('select', node.target);
                if (node.attributes.reportType == '0') {
                    // 分类
                    $('#mm').menu('show', {
                        left : e.pageX,
                        top : e.pageY
                    });
                } else {
                    // 模板， 只定义删除操作
                    $('#mm1').menu('show', {
                        left : e.pageX,
                        top : e.pageY
                    });
                }
                type="nRoot";
            },
            onDblClick : function(node) {
                if (node._parentId == '-1') {
                    // 根节点不允许编辑
                    return;
                }
                _nodeId.tree('beginEdit', node.target);
                type="nRoot";
            },
            onBeforeLoad : function(node, param) {
            },
            onBeforeEdit : function(node) {
                _currentEditNodeText = node.text;
            },
            onAfterEdit : function(node) {
                if (null == _currentEditNodeText
                    || _currentEditNodeText == node.text) {
                    if (node.id.indexOf('xjfl_') != 0) {
                        return;
                    }
                }
                if (node.id.indexOf('xjfl_') == 0) {
                    node.id = "";
                }
                var args = {
                    sysId : _sysId,
                    id : node.id,
                    text : node.text,
                    reportType : node.attributes.reportType,
                    _parentId : node._parentId,
                    attributes : {
                        "reportType" : node.attributes.reportType
                    }
                };
                // 刷新父节点
                $.ajax({
                    url : _url + "/insertreporttree",
                    type : 'post',
                    dataType : 'json',
                    data : {
                        param : JSON.stringify(args)
                    },
                    success : function(result) {
                        if (result.flag == "success") {
                            // 保存成功 ， 刷新其父节点
                            _nodeId.tree({
                                url : _url + "/gettree/-1/null?sysId="+sysId
                            });
                            $.messager.show({
                                title : commonLang.tip.alert,
                                msg : commonLang.optip.saveSuccess,
                                timeout : 4000,
                                showType : 'slide'
                            });
                        } else {
                            $.messager.show({
                                title : commonLang.tip.alert,
                                msg : commonLang.optip.saveFailure,
                                timeout : 4000,
                                showType : 'slide'
                            });
                        }
                    }
                });
            },
            formatter : function(node) {
                return '<span title="' + node.text + '">' + node.text
                    + '</span>';
            }
        });
};


//加载报表管理根节点树
/**
 * remind, 提示 templatenotexist 该模板不存在！ savesuccess 保存成功 savefailure 保存失敗
 */
ReportManager.prototype.loadReportTreeRoot = function() {
    var _self = this;
    var _nodeId = this.rootNodeId;
    var _url = this.url;
    var _sysId = this.sysId;
    var _currentEditNodeText = null;
    this.rootNodeId.tree({
        checkbox : false, // 是否带复选框
        lines : true, // 线条
        method : 'post',
        url : this.url + "/gettree/-1/root?sysId="+_sysId,
        dataType : "json",
        /* 数据格式 */
        onCheck : function(node, checked) {
            // 勾选复选框时触发
            type="root";
        },
        formatter : function(node) {
            if (node._parentId == "-1") {
                _self._rootId = node.id;
            }
            if (node.attributes && node.attributes.s) {
                return '<a style="color:#fff;font-weight:normal;background:#3399ff;padding:0 4px;">'
                    + node.text + '</a>';
            } else {
                return node.text;
            }
        },
        loadFilter : function(data) {
            // 过滤后台返回的数据，处理不同JSON结构
            if (data.data) {
                return data.data;
            } else {
                return data;
            }
        },
        onClick : function(node) {
            if(orgId == "ORG_ROOT"){
                $("#importId").show();
            }else{
                $("#importId").hide();
            }
            type="root";
            _nodeId.tree('select', node.target);
            // 模板， 加载其所对应的模板
            if (node.attributes.reportType == '1') {
                if (node.attributes.cptFileName == null
                    || !node.attributes.cptFileExist) {
                    $.messager.alert(commonLang.tip.alert,
                        commonLang.tip.templateNotExist, 'warning');
                    return;
                }
                lantopFineReport.submit({
                    SQL : "SELECT ' ' FROM DUAL",
                    reportlet : node.attributes.cptFileName
                });
            }
        },
        onContextMenu : function(e, node) {
            if(orgId == "ORG_ROOT"){
                e.preventDefault();
                // 查找节点
                _nodeId.tree('select', node.target);
                if (node.attributes.reportType == '0') {
                    // 分类
                    $('#mm').menu('show', {
                        left : e.pageX,
                        top : e.pageY
                    });
                } else {
                    // 模板， 只定义删除操作
                    $('#mm1').menu('show', {
                        left : e.pageX,
                        top : e.pageY
                    });
                }
            }
            type="root";
        },
        onDblClick : function(node) {
            if(orgId == "ORG_ROOT"){
                if (node._parentId == '-1') {
                    // 根节点不允许编辑
                    return;
                }
                _nodeId.tree('beginEdit', node.target);
            }
            type="root";
        },
        onBeforeLoad : function(node, param) {
        },
        onBeforeEdit : function(node) {
            _currentEditNodeText = node.text;
        },
        onAfterEdit : function(node) {
            if (null == _currentEditNodeText
                || _currentEditNodeText == node.text) {
                if (node.id.indexOf('xjfl_') != 0) {
                    return;
                }
            }
            if (node.id.indexOf('xjfl_') == 0) {
                node.id = "";
            }
            var args = {
                sysId : _sysId,
                id : node.id,
                text : node.text,
                reportType : node.attributes.reportType,
                _parentId : node._parentId,
                attributes : {
                    "reportType" : node.attributes.reportType
                }
            };
            // 刷新父节点
            $.ajax({
                url : _url + "/insertreporttree",
                type : 'post',
                dataType : 'json',
                data : {
                    param : JSON.stringify(args)
                },
                success : function(result) {
                    if (result.flag == "success") {
                        // 保存成功 ， 刷新其父节点
                        _nodeId.tree({
                            url : _url + "/gettree/-1/root?sysId="+_sysId
                        });
                        $.messager.show({
                            title : commonLang.tip.alert,
                            msg : commonLang.optip.saveSuccess,
                            timeout : 4000,
                            showType : 'slide'
                        });
                    } else {
                        $.messager.show({
                            title : commonLang.tip.alert,
                            msg : commonLang.optip.saveFailure,
                            timeout : 4000,
                            showType : 'slide'
                        });
                    }
                }
            });
        },
        formatter : function(node) {
            return '<span title="' + node.text + '">' + node.text
                + '</span>';
        }
    });
};


//重新加载当前组织树
ReportManager.prototype.reLoadReportTree = function() {
    this.nodeId.tree({
        url : this.url + "/gettree/-1/null?sysId="+this.sysId
    });
};

function reLoadTree() {
    reportManager.reLoadReportTree();
}

//重新加载根组织树
ReportManager.prototype.reLoadReportTreeRoot = function() {
    this.rootNodeId.tree({
        url : this.url + "/gettree/-1/root?sysId="+this.sysId
    });
};

function reLoadTreeRoot() {
    reportManager.reLoadReportTreeRoot();
}


// 新增模板
ReportManager.prototype.configuration = function() {
    var _nodeId;
    if(type == "root"){
        _nodeId = this.rootNodeId;
    }else{
        _nodeId = this.nodeId;
    }
    var template = _nodeId.tree('getSelected');
    if (null == template || template.attributes.reportType == '0') {
        $.messager.alert(commonLang.tip.alert,
            commonLang.tip.selectTemplateConfig, 'warning');
        return;
    }
    // 获取报表应输出字段, 对于导入的报表模板，需要从cpt文件中获取暂时不处理
    // 导入报表模板，获取代码
    // ($($(window.frames["reportView"].document).find("#r-0-0").find("td")[0]).text())
    // 目前直接从节点中获取
    var outPutFields;
    if (template.attributes.hasField) {
        outPutFields = template.attributes.fields;
    } else {
        outPutFields = $(
            $(window.frames["reportView"].document).find("#r-0-0").find(
                "td")[0]).text();
        if ("" == outPutFields) {// 无输出字段
            $.messager.alert(commonLang.tip.alert,
                commonLang.tip.templateNoFiled, 'warning');
            return;
        }
    }
    outPutFields = encodeURI(encodeURI(outPutFields));// 输出字段

    var dialogId = "formConfigReport";
    var config = new CommonDialog(dialogId, "900", "500",
        "platform/ReportFormConfigController/toConfigJsp?dialogId="
        + dialogId + "&sysId=" + this.sysId + "&outPutFields="
        + outPutFields + "&templateId=" + template.id,
        commonLang.tip.templateConfig);
    config.show();
};
